const axios = require('axios');
const jwt = require('jsonwebtoken');

// Base URL for the API
const BASE_URL = 'http://localhost:3003';

// Generate a valid JWT token for testing (using the same secret as in the app)
const JWT_SECRET = 'financeapp_jwt_secret'; // This should match the secret in your .env file
const TEST_USER_ID = 1;

// Generate a valid token
const TEST_JWT_TOKEN = jwt.sign({ userId: TEST_USER_ID }, JWT_SECRET, { expiresIn: '24h' });

async function testAccountBalances() {
  try {
    console.log('Testing Account Management API...');
    
    // 1. Create a few accounts with different types and balances
    console.log('\n1. Creating accounts...');
    
    const accounts = [
      { name: '现金钱包', type: '现金', balance: 500.00 },
      { name: '招商银行储蓄卡', type: '银行卡', balance: 15000.00 },
      { name: '中信银行信用卡', type: '信用卡', balance: -8000.00 },
      { name: '支付宝账户', type: '其他', balance: 2500.00 }
    ];
    
    const createdAccounts = [];
    
    for (const accountData of accounts) {
      try {
        const response = await axios.post(`${BASE_URL}/api/accounts`, accountData, {
          headers: {
            'Authorization': `Bearer ${TEST_JWT_TOKEN}`
          }
        });
        
        console.log(`✓ Created account: ${response.data.account.name} (${response.data.account.type}) - Balance: ${response.data.account.balance}`);
        createdAccounts.push(response.data.account);
      } catch (error) {
        console.error(`✗ Failed to create account ${accountData.name}:`, error.response?.data || error.message);
      }
    }
    
    // 2. Get all accounts
    console.log('\n2. Retrieving all accounts...');
    try {
      const response = await axios.get(`${BASE_URL}/api/accounts`, {
        headers: {
          'Authorization': `Bearer ${TEST_JWT_TOKEN}`
        }
      });
      
      console.log(`✓ Retrieved ${response.data.accounts.length} accounts:`);
      response.data.accounts.forEach(account => {
        console.log(`  - ${account.name} (${account.type}): ${account.balance} ${account.currency}`);
      });
    } catch (error) {
      console.error('✗ Failed to retrieve accounts:', error.response?.data || error.message);
    }
    
    // 3. Get account summary
    console.log('\n3. Getting account summary...');
    try {
      const response = await axios.get(`${BASE_URL}/api/accounts/summary`, {
        headers: {
          'Authorization': `Bearer ${TEST_JWT_TOKEN}`
        }
      });
      
      console.log('✓ Account Summary:');
      console.log(`  Total Balance: ${response.data.summary.total_balance} ${response.data.summary.currency}`);
      console.log('  By Account Type:');
      response.data.summary.by_type.forEach(typeSummary => {
        console.log(`    ${typeSummary.type}: ${typeSummary.count} accounts, Total: ${typeSummary.total_balance}`);
      });
    } catch (error) {
      console.error('✗ Failed to get account summary:', error.response?.data || error.message);
    }
    
    // 4. Update an account balance
    console.log('\n4. Updating an account balance...');
    if (createdAccounts.length > 0) {
      const accountId = createdAccounts[0].id;
      try {
        const response = await axios.put(`${BASE_URL}/api/accounts/${accountId}`, {
          balance: 750.00 // Update cash wallet balance
        }, {
          headers: {
            'Authorization': `Bearer ${TEST_JWT_TOKEN}`
          }
        });
        
        console.log(`✓ Updated account ${response.data.account.name}: New balance is ${response.data.account.balance}`);
      } catch (error) {
        console.error('✗ Failed to update account:', error.response?.data || error.message);
      }
    }
    
    // 5. Get updated summary
    console.log('\n5. Getting updated account summary...');
    try {
      const response = await axios.get(`${BASE_URL}/api/accounts/summary`, {
        headers: {
          'Authorization': `Bearer ${TEST_JWT_TOKEN}`
        }
      });
      
      console.log('✓ Updated Account Summary:');
      console.log(`  Total Balance: ${response.data.summary.total_balance} ${response.data.summary.currency}`);
      console.log('  By Account Type:');
      response.data.summary.by_type.forEach(typeSummary => {
        console.log(`    ${typeSummary.type}: ${typeSummary.count} accounts, Total: ${typeSummary.total_balance}`);
      });
    } catch (error) {
      console.error('✗ Failed to get updated account summary:', error.response?.data || error.message);
    }
    
    console.log('\n✓ All tests completed successfully!');
  } catch (error) {
    console.error('Test failed:', error.message);
  }
}

// Run the test
testAccountBalances();